package com.fjwt.gz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.db.dto.FansAddressDTO;
import com.fjwt.gz.db.entity.FansAddressEntity;
import com.fjwt.gz.db.vo.FansAddressVO;
import com.fjwt.gz.service.mapper.FansAddressMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 用户地址表 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class FansAddressService extends ServiceImpl<FansAddressMapper, FansAddressEntity> {


    @Resource
    private FansAddressMapper fansAddressMapper;

    /**
     * 获取用户地址列表
     **/
    public IPage<FansAddressVO> getAddressList(IPage<?> page, Long fansId, String appId) {
         IPage<FansAddressEntity> addressList = fansAddressMapper.getAddressList(page, fansId, appId);
        List<FansAddressEntity> records = addressList.getRecords();
        //FansAddressEntity转Vo
        List<FansAddressVO> fansAddressVOList = records.stream().map(entity -> {
            FansAddressVO vo = BeanUtil.copyProperties(entity, FansAddressVO.class);
            return vo;
        }).toList();
        //封装
        IPage<FansAddressVO> pageVo = new Page<>();
        pageVo.setRecords(fansAddressVOList);
        pageVo.setTotal(addressList.getTotal());
        pageVo.setCurrent(addressList.getCurrent());
        pageVo.setSize(addressList.getSize());
        return pageVo;
    }

    /**
     * 添加用户地址
     **/
    @Transactional(rollbackFor = Exception.class)
    public void addAddress(FansAddressDTO dto) {
        // 参数校验
        if (dto.getFansId() == null || dto.getAppId() == null) {
            throw new BizException("参数异常，请检查！");
        }

        if (ObjectUtil.isEmpty(dto.getContactName()) || ObjectUtil.isEmpty(dto.getContactPhone()) ||
                    ObjectUtil.isEmpty(dto.getProvinceCode()) || ObjectUtil.isEmpty(dto.getProvinceName()) ||
                        ObjectUtil.isEmpty(dto.getCityCode()) || ObjectUtil.isEmpty(dto.getCityName()) ||
                            ObjectUtil.isEmpty(dto.getAreaCoe()) || ObjectUtil.isEmpty(dto.getAreaName()) ||
                                ObjectUtil.isEmpty(dto.getAddress())){
            throw new BizException("请完善个人信息");
        }
        
        FansAddressEntity fansAddressEntity = BeanUtil.copyProperties(dto, FansAddressEntity.class);
        LambdaQueryWrapper<FansAddressEntity> gw = FansAddressEntity.gw();
        gw.eq(FansAddressEntity::getFansId, fansAddressEntity.getFansId())
                .eq(FansAddressEntity::getAppId, fansAddressEntity.getAppId());
        
        // 获取该用户地址
        List<FansAddressEntity> addressList = fansAddressMapper.selectList(gw);
        if (CollUtil.isEmpty(addressList)) {
            fansAddressEntity.setIsDefault(0);
            fansAddressMapper.insert(fansAddressEntity);
            return;
        }

        // 默认地址处理逻辑
        if (fansAddressEntity.getIsDefault() == 0) {
            List<FansAddressEntity> defaultAddress = addressList.stream()
                    .filter(entity -> entity.getIsDefault() == 0).toList();

            if (CollUtil.isNotEmpty(defaultAddress)) {
                FansAddressEntity existingDefault = defaultAddress.get(0);
                existingDefault.setIsDefault(1);
                fansAddressMapper.updateById(existingDefault);
            }
        }
        fansAddressMapper.insert(fansAddressEntity);
    }

    /**
     * 更新用户地址
     **/
    @Transactional(rollbackFor = Exception.class)
    public void updateAddress(FansAddressDTO dto, Long fansId) {
        if (ObjectUtil.isEmpty(dto.getContactName()) || ObjectUtil.isEmpty(dto.getContactPhone()) ||
                ObjectUtil.isEmpty(dto.getProvinceCode()) || ObjectUtil.isEmpty(dto.getProvinceName()) ||
                ObjectUtil.isEmpty(dto.getCityCode()) || ObjectUtil.isEmpty(dto.getCityName()) ||
                ObjectUtil.isEmpty(dto.getAreaCoe()) || ObjectUtil.isEmpty(dto.getAreaName()) ||
                ObjectUtil.isEmpty(dto.getAddress())){
            throw new BizException("请完善个人信息");
        }
        FansAddressEntity fansAddressEntity = BeanUtil.copyProperties(dto, FansAddressEntity.class);
        FansAddressEntity existEntity = fansAddressMapper.selectById(fansAddressEntity.getFansAddressId());
        if (ObjectUtils.isEmpty(existEntity)) {
            throw new BizException("所选数据异常，请重试");
        }
        if (!fansId.equals(existEntity.getFansId())) {
            throw new BizException("不可修改非本人地址");
        }
        if (Objects.equals(fansAddressEntity.getIsDefault(), existEntity.getIsDefault())) {
            //如果默认地址没变，则直接更新
            fansAddressMapper.updateById(fansAddressEntity);
            return;
        }
        if (existEntity.getIsDefault() == 0) {
            //如果数据库是默认地址，而传进来的则是不是默认地址，抛出异常
            throw new BizException("默认地址不能改为非默认地址");
        }
        if (existEntity.getIsDefault() == 1) {
            //传进来的是默认地址，把非默认地址改为了默认地址
            LambdaQueryWrapper<FansAddressEntity> gw = FansAddressEntity.gw();
            gw.eq(FansAddressEntity::getFansId, fansId);
            gw.eq(FansAddressEntity::getIsDefault, 0);
            FansAddressEntity fansAddress = fansAddressMapper.selectOne(gw);
            if (fansAddress != null) {
                fansAddress.setIsDefault(1);
                fansAddressMapper.updateById(fansAddress);
            }
            fansAddressMapper.updateById(fansAddressEntity);
        }
    }


    /**
     * 查看用户地址详情
     **/
    public FansAddressVO getAddressDetail(Long fansAddressId, Long fansId) {
        FansAddressEntity fansAddressEntity = fansAddressMapper.selectById(fansAddressId);
        if (ObjectUtils.isEmpty(fansAddressEntity) || !fansId.equals(fansAddressEntity.getFansId())){
            throw new BizException("不可查看非本人地址");
        }
        FansAddressVO vo = BeanUtil.copyProperties(fansAddressEntity, FansAddressVO.class);
        return vo;
    }
    /**
     * 删除用户地址
     **/
    public void delAddress(Long fansAddressId, Long fansId) {
        FansAddressEntity fansAddressEntity = fansAddressMapper.selectById(fansAddressId);
        if (ObjectUtils.isEmpty(fansAddressEntity) || !fansId.equals(fansAddressEntity.getFansId())){
            throw new BizException("不可删除非本人地址");
        }
        fansAddressMapper.deleteById(fansAddressId);
    }

}
